package com.example.shuiyin.service.impl;

import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import com.example.shuiyin.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
@Slf4j
public class WxServiceImpl implements WxService {
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    @Value("${wx.appid}")
    private String appId;
    
    @Value("${wx.secret}")
    private String secret;
    
    @Override
    @SuppressWarnings("unchecked")
    public String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId 
                + "&secret=" + secret 
                + "&js_code=" + code 
                + "&grant_type=authorization_code";
        
        try {
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            Map<String, Object> body = (Map<String, Object>) response.getBody();
            
            if (body == null) {
                throw new AppException("微信服务器响应为空", ErrorCode.INTERNAL_SERVER_ERROR);
            }
            
            Integer errcode = (Integer) body.get("errcode");
            if (errcode != null && errcode != 0) {
                log.error("微信登录失败: {}", body);
                throw new AppException("微信登录失败: " + body.get("errmsg"), ErrorCode.BAD_REQUEST);
            }
            
            return (String) body.get("openid");
        } catch (Exception e) {
            log.error("微信登录异常: {}", e.getMessage(), e);
            throw new AppException("微信登录异常: " + e.getMessage(), ErrorCode.INTERNAL_SERVER_ERROR);
        }
    }
} 